<template>
  <q-page class="q-pa-md">
    <div class="q-pb-md text-h5">{{pageTitle}} <span class="text-subtitle1">{{pageSubTitle}}</span></div>
    <div class="q-pa-sm shadow-2 q-mb-md">
      <div class="btn q-gutter-sm">
        <q-btn @click="detailNav.goBackToList" color="primary" icon="arrow_back" outline :title="$t('返回')" />
        <q-btn @click="loadModelData" color="primary" dense icon="refresh" outline :title="$t('刷新')" :disable="loadingState"
          :loading="loadingState" v-if="isViewOrEditMode" />
      </div>
    </div>
    <div class="shadow-2">
      <q-tabs active-color="primary" align="left" dense indicator-color="primary" v-model="showingTabPanel">
        <q-tab :label="$t('主档详情')" name="code" no-caps/>
        <q-tab :label="$t('代码明细')" name="codeLine" no-caps/>
        <q-tab :label="tabTitle" name="codeDetail" v-if="isLineTabDisp" no-caps/>
      </q-tabs>
      <q-separator />
      <q-tab-panels v-model="showingTabPanel">
        <q-tab-panel class="q-pa-sm" name="code">
          <div class="row q-col-gutter-sm q-pt-sm">
            <div class="col-12 col-sm-6 col-md-4 col-lg-3">
              <span>{{$t('代码ID')}}</span>
              <q-input :hide-bottom-space="true" dense :maxlength="30" outlined readonly square stack-label
                v-model="$d.form.codeId"></q-input>
            </div>
          </div>
          <div class="row q-col-gutter-sm q-pt-sm">
            <div class="col-12 col-sm-6 col-md-4 col-lg-3">
              <span>{{$t('代码名称')}}</span>
              <q-input :hide-bottom-space="true" dense :maxlength="30" outlined readonly square stack-label
                v-model="$d.form.codeName"></q-input>
            </div>
            <div class="col-12 col-sm-6 col-md-4 col-lg-3">
              <span>{{$t('不可修改')}}</span>
              <div class="bg-grey-3">
                <q-checkbox v-model="$d.form.immutable" disable class="full-width q-pa-xs" color="primary"
                  dense />
              </div>
            </div>
            <div class="col-12">
              <span>{{$t('描述')}}</span>
              <q-input :dense="true" :hide-bottom-space="true" autogrow :maxlength="300" outlined readonly square
                stack-label type="textarea" v-model="$d.form.descriptions"></q-input>
            </div>
          </div>
        </q-tab-panel>

        <q-tab-panel class="q-pa-none" name="codeLine">
          <q-table :columns="columnsInfoCodeLine" :rows="$d.form.lines" v-model:pagination="$d.paginationInfoCodeLine"
            :hide-pagination="true" @row-dblclick="(evt,row)=>{lineDetailNav.goViewLine(row.codeLineId)}" dense
            row-key="codeLineId" separator="cell" flat :visible-columns="$d.visibleColumnsCodeLine" :loading="loadingState"
            color="primary">
            <template v-slot:top="props">
              <div class="q-gutter-sm">
                <q-btn @click="createCodeLine" color="primary" icon="add" :label="$t('新建明细')" no-caps
                  v-if="fx.hasModifyRight('Comm.Code.Edit') && !$d.form.immutable && !loadingState" :disable="loadingState" />
              </div>
              <q-space />
              <table-col-options-cfg v-model:table-columns="columnsInfoCodeLine"
                v-model:visible-columns="$d.visibleColumnsCodeLine"
                @update-col-options-for-save="(optToSave)=>saveDetailColOptions('codeLine',optToSave)" class="q-ml-sm">
              </table-col-options-cfg>
              <q-btn :icon="props.inFullscreen ? 'fullscreen_exit' : 'fullscreen'" @click="props.toggleFullscreen"
                :title="props.inFullscreen ? $t('退出全屏') : $t('全屏显示')" class="q-ml-sm" dense flat :ripple="false" />
            </template>
            <template v-slot:body-cell-operation="props">
              <q-td :props="props" auto-width>
                <q-btn :dense="true" @click="lineDetailNav.goViewLine(props.row.codeLineId)" color="primary"
                  :label="$t('查看')" :disable="loadingState" class="btn-in-row" no-caps/>
                <q-btn :dense="true" @click="lineDetailNav.goEditLine(props.row.codeLineId)" color="primary" no-caps
                  class="q-ml-xs btn-in-row" :label="$t('编辑')" v-if="fx.hasModifyRight('Comm.Code.Edit') && !$d.form.immutable"
                  :disable="loadingState"/>
                <q-btn :dense="true" @click="deleteCodeLine(props.row.codeLineId)" class="q-ml-xs btn-in-row" color="red" no-caps
                  :label="$t('删除')" v-if="fx.hasModifyRight('Comm.Code.Edit') && !$d.form.immutable" :disable="loadingState" />
              </q-td>
            </template>
            <template v-slot:body-cell-isEnabled="props">
              <q-td :props="props" auto-width>
                <q-badge :color="props.row.isEnabled?'positive':'negative'"
                  :label="props.row.isEnabled ? $t('有效') : $t('无效')" />
              </q-td>
            </template>
            <template v-slot:no-data>
              <div class="full-width text-center">
                <q-icon name="error_outline" /> {{$t('无数据')}}
              </div>
            </template>
            <template v-slot:bottom>
              <paging-bar :loading-state="loadingState" :pageNo="$d.paginationInfoCodeLine.page"
                :pageSize="$d.paginationInfoCodeLine.rowsPerPage" :totalAmount="$d.form.lines.length"
                @go-to-page="(pageNo)=>{$d.paginationInfoCodeLine.page=pageNo}"
                @pagesize-changed="(pageSize)=>{$d.paginationInfoCodeLine.rowsPerPage=pageSize;saveDetailPageSize('codeLine',pageSize)}"
                :show-refresh-button="false" :restrict-input-page-no="true" />
            </template>
          </q-table>
        </q-tab-panel>
        <q-tab-panel class="q-pa-sm" name="codeDetail">
          <div class="q-gutter-sm">
            <id-create-update-disp class="float-right" :model-with-create-update="lineDetailInfo.lineForm"
              model-id="codeLineId" />
            <q-btn @click="lineDetailNav.backToListTab" color="primary" icon="close" outline :title="$t('关闭')"
              v-if="isLineViewMode" />
            <q-btn @click="loadLineModelData" color="primary" dense
              icon="refresh" outline :title="$t('刷新')" :disable="lineLoadingState"
              :loading="lineLoadingState" v-if="isLineViewOrEditMode" />
            <q-btn @click="doCodeLineSubmit" color="primary" :label="$t('确定')" v-if="isLineCreateOrEditMode"
              :loading="submittingState" :disable="loadingState" no-caps/>
            <q-btn @click="lineDetailNav.cancelLineSubmit" :label="$t('取消')" outline v-if="isLineCreateOrEditMode"
              :disable="submittingState" color="primary" no-caps/>
            <q-btn @click="lineDetailNav.turnLineToEditMode" color="primary" icon="edit" :label="$t('编辑')"
              v-if="fx.hasModifyRight('Comm.Code.Edit') && isLineViewMode && !$d.form.immutable" no-caps
              :disable="lineLoadingState" />
            <q-btn @click="deleteCodeLine(lineDetailInfo.lineItemId)" color="red" icon="delete_outline" :label="$t('删除')"
              v-if="fx.hasModifyRight('Comm.Code.Edit') && isLineViewMode && !$d.form.immutable" no-caps
              :disable="lineLoadingState" />
          </div>
          <q-banner class="text-white bg-red q-mt-sm" dense inline-actions v-if="lineSvrErrMsg">
            {{ lineSvrErrMsg }}
            <template v-slot:action>
              <q-btn flat icon="close" size="sm" dense @click="lineSvrErrMsg=''" />
            </template>
          </q-banner>
          <div class="q-pt-sm">
            <div class="row q-col-gutter-sm q-pb-sm">
              <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                <q-icon color="red" name="fas fa-asterisk" size="10px" />
                <span>{{$t('代码值')}}</span>
                <easy-input :error="v$.codeValue.$error" :error-message="e$(v$.codeValue.$errors)"
                  :maxlength="100" :readonly="isLineViewMode" v-model="lineDetailInfo.lineForm.codeValue"></easy-input>
              </div>
              <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                <span>{{$t('排序值')}}</span>
                <easy-input :error="v$.sortId.$error" :error-message="e$(v$.sortId.$errors)"
                  :readonly="isLineViewMode" v-model="lineDetailInfo.lineForm.sortId"></easy-input>
              </div>
              <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                <span>{{$t('有效')}}</span>
                <div class="bg-grey-3">
                  <q-checkbox dense class="full-width q-pa-xs" color="primary" :disable="isLineViewMode"
                    v-model="lineDetailInfo.lineForm.isEnabled" />
                </div>
              </div>
            </div>
            <div class="row q-col-gutter-sm q-pb-sm">
              <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                <q-icon color="red" name="fas fa-asterisk" size="10px" />
                <span>{{ $d.codeNameDisp[0] ?? $t('显示名称{number}',{number: 1}) }}</span>
                <q-input :error="v$.codeName1.$error" :error-message="e$(v$.codeName1.$errors)" :hide-bottom-space="true" dense
                  :maxlength="100" no-error-icon outlined :readonly="isLineViewMode" square stack-label
                  v-model="lineDetailInfo.lineForm.codeName1"></q-input>
              </div>
              <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                <span>{{ $d.codeNameDisp[1] ?? $t('显示名称{number}',{number: 2}) }}</span>
                <q-input :hide-bottom-space="true" dense :maxlength="100" outlined
                  :readonly="isLineViewMode" square stack-label
                  v-model="lineDetailInfo.lineForm.codeName2"></q-input>
              </div>
              <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                <span>{{ $d.codeNameDisp[2] ?? $t('显示名称{number}',{number: 3}) }}</span>
                <q-input :hide-bottom-space="true" dense :maxlength="100" outlined
                  :readonly="isLineViewMode" square stack-label
                  v-model="lineDetailInfo.lineForm.codeName3"></q-input>
              </div>
              <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                <span>{{ $d.codeNameDisp[3] ?? $t('显示名称{number}',{number: 4}) }}</span>
                <q-input :hide-bottom-space="true" dense :maxlength="100" outlined
                  :readonly="isLineViewMode" square stack-label
                  v-model="lineDetailInfo.lineForm.codeName4"></q-input>
              </div>
              <div class="col-12 col-sm-6 col-md-4 col-lg-3">
                <span>{{ $d.codeNameDisp[4] ?? $t('显示名称{number}',{number: 5}) }}</span>
                <q-input :hide-bottom-space="true" dense :maxlength="100" outlined
                  :readonly="isLineViewMode" square stack-label
                  v-model="lineDetailInfo.lineForm.codeName5"></q-input>
              </div>
            </div>
            <div class="row q-col-gutter-sm">
              <div class="col-12">
                <span>{{ $t('描述') }}</span>
                <q-input :hide-bottom-space="true" autogrow dense :maxlength="300" outlined
                  :readonly="isLineViewMode" square stack-label type="textarea"
                  v-model="lineDetailInfo.lineForm.descriptions"></q-input>
              </div>
            </div>
          </div>
        </q-tab-panel>
      </q-tab-panels>
    </div>
  </q-page>
</template>

<script lang="ts">
export default {
  name: 'codeStd'
}
</script>

<script lang="ts" setup>
import {useTitleHelper} from '../../hooks/titleHelper'
import {useDetailHelper} from '../../hooks/detailHelper'
import {computed, reactive, ref} from 'vue'
import {Code, CodeLine} from '../../defs/code'
import {useLineDetailHelper} from '../../hooks/lineDetailHelper'
import {ColumnInfo} from '../../defs/comm'
import useVuelidate from '@vuelidate/core'
import _ from 'lodash'
import {useI18n} from 'vue-i18n'
import EasyInput from 'src/lib/components/EasyInput.vue'

const {t} = useI18n({useScope:'global'})

const pageTitle = t('代码设置')
useTitleHelper(pageTitle)

let serverErrorMessage = ref('')
// 当前正在显示的tab
let showingTabPanel = ref('code')

let $d = reactive({
  // 表单数据
  form: {} as Code,
  visibleColumnsCodeLine: [] as string[],
  paginationInfoCodeLine: {
    // 页码
    page: 1,
    // 每页多少条
    rowsPerPage: 40,
    // 是否倒序
    descending: false,
    // 按什么排序
    sortBy: 'sortId'
  },
  codeNameDisp: [] as string[]
})

let loadingState = ref(false)
// 加载数据
const loadModelData = function () {
  $d.codeNameDisp = []
  loadingState.value = true
  $f.axios
    .get<Code>('/comm/code/get-code/' + detailInfo.itemId)
    .then((resp) => {
      $d.form = resp.data
      // 判断是否需要关闭详情页
      if (lineDetailInfo.lineItemId) {
        if (!_.find($d.form.lines, { codeLineId: lineDetailInfo.lineItemId })) {
          lineDetailNav.backToListTab()
        }
      }
      if ($d.form.codeNameTitles) {
        $d.codeNameDisp = _.split($d.form.codeNameTitles, '|')
      }
      columnsInfoCodeLine = [
        {
          label: t('操作'),
          name: 'operation',
          field: 'operation',
          align: 'left',
          defOrder: 1,
          defVisible: true
        },
        {
          label: t('排序值'),
          name: 'sortId',
          field: 'sortId',
          align: 'left',
          defOrder: 2,
          defVisible: true
        },
        {
          label: t('代码值'),
          name: 'codeValue',
          field: 'codeValue',
          align: 'left',
          defOrder: 3,
          defVisible: true
        },
        // {
        //   label: $d.codeNameDisp[0]??'显示名称1',
        //   name: 'codeName1',
        //   field: 'codeName1',
        //   align: 'left',
        //   defOrder: 4,
        //   defVisible: true
        // },
        // {
        //   label: $d.codeNameDisp[1]??'显示名称2',
        //   name: 'codeName2',
        //   field: 'codeName2',
        //   align: 'left',
        //   defOrder: 5,
        //   defVisible: true
        // },
        // {
        //   label: $d.codeNameDisp[2]??'显示名称3',
        //   name: 'codeName3',
        //   field: 'codeName3',
        //   align: 'left',
        //   defOrder: 6,
        //   defVisible: true
        // },
        // {
        //   label: $d.codeNameDisp[3]??'显示名称4',
        //   name: 'codeName4',
        //   field: 'codeName4',
        //   align: 'left',
        //   defOrder: 7,
        //   defVisible: true
        // },
        // {
        //   label: $d.codeNameDisp[4]??'显示名称5',
        //   name: 'codeName5',
        //   field: 'codeName5',
        //   align: 'left',
        //   defOrder: 8,
        //   defVisible: true
        // },
        {
          label: t('是否有效'),
          name: 'isEnabled',
          field: 'isEnabled',
          align: 'left',
          defOrder: 9,
          defVisible: true
        },
        {
          label: t('描述'),
          name: 'descriptions',
          field: 'descriptions',
          align: 'left',
          defOrder: 10,
          defVisible: true
        }
      ]
      columnsInfoCodeLine.splice(3,0,  {
          label: $d.codeNameDisp[0]??t('显示名称{number}',{number: 1}),
          name: 'codeName1',
          field: 'codeName1',
          align: 'left',
          defOrder: 4,
          defVisible: true
        },
        {
          label: $d.codeNameDisp[1]??t('显示名称{number}',{number: 2}),
          name: 'codeName2',
          field: 'codeName2',
          align: 'left',
          defOrder: 5,
          defVisible: true
        },
        {
          label: $d.codeNameDisp[2]??t('显示名称{number}',{number: 3}),
          name: 'codeName3',
          field: 'codeName3',
          align: 'left',
          defOrder: 6,
          defVisible: true
        },
        {
          label: $d.codeNameDisp[3]??t('显示名称{number}',{number: 4}),
          name: 'codeName4',
          field: 'codeName4',
          align: 'left',
          defOrder: 7,
          defVisible: true
        },
        {
          label: $d.codeNameDisp[4]??t('显示名称{number}',{number: 5}),
          name: 'codeName5',
          field: 'codeName5',
          align: 'left',
          defOrder: 8,
          defVisible: true
        })
      let colsInfoSaved = loadDetailColOptions('codeLine', columnsInfoCodeLine)
      $d.visibleColumnsCodeLine = colsInfoSaved[1]

    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      loadingState.value = false
    })
}

// 主档帮助方法
const {
  detailInfo,
  detailStatus,
  detailNav,
  dlAssist
} = useDetailHelper('/comm/cfg/code',
  $d.form,
  null,
  '/comm/cfg/code',
  '/comm/cfg/code/detail',
  null,
  null,
  loadModelData,
  serverErrorMessage
)

const {
  saveDetailColOptions,
  saveDetailPageSize,
  loadDetailColOptions,
  loadDetailPageSize
} = dlAssist


// codeLine列参数
let columnsInfoCodeLine: ColumnInfo[] = [
  {
    label: t('操作'),
    name: 'operation',
    field: 'operation',
    align: 'left',
    defOrder: 1,
    defVisible: true
  },
  {
    label: t('排序值'),
    name: 'sortId',
    field: 'sortId',
    align: 'left',
    defOrder: 2,
    defVisible: true
  },
  {
    label: t('代码值'),
    name: 'codeValue',
    field: 'codeValue',
    align: 'left',
    defOrder: 3,
    defVisible: true
  },
  // {
  //   label: $d.codeNameDisp[0]??'显示名称1',
  //   name: 'codeName1',
  //   field: 'codeName1',
  //   align: 'left',
  //   defOrder: 4,
  //   defVisible: true
  // },
  // {
  //   label: $d.codeNameDisp[1]??'显示名称2',
  //   name: 'codeName2',
  //   field: 'codeName2',
  //   align: 'left',
  //   defOrder: 5,
  //   defVisible: true
  // },
  // {
  //   label: $d.codeNameDisp[2]??'显示名称3',
  //   name: 'codeName3',
  //   field: 'codeName3',
  //   align: 'left',
  //   defOrder: 6,
  //   defVisible: true
  // },
  // {
  //   label: $d.codeNameDisp[3]??'显示名称4',
  //   name: 'codeName4',
  //   field: 'codeName4',
  //   align: 'left',
  //   defOrder: 7,
  //   defVisible: true
  // },
  // {
  //   label: $d.codeNameDisp[4]??'显示名称5',
  //   name: 'codeName5',
  //   field: 'codeName5',
  //   align: 'left',
  //   defOrder: 8,
  //   defVisible: true
  // },
  {
    label: t('是否有效'),
    name: 'isEnabled',
    field: 'isEnabled',
    align: 'left',
    defOrder: 9,
    defVisible: true
  },
  {
    label: t('描述'),
    name: 'descriptions',
    field: 'descriptions',
    align: 'left',
    defOrder: 10,
    defVisible: true
  }
]

const {
  isViewOrEditMode,
  pageSubTitle
} = detailStatus

let lineLoadingState = ref(false)
// 加载明细详情
const loadLineModelData = function () {
  lineLoadingState.value = true
  $f.axios
    .get<CodeLine>('/comm/code/get-codeline/' + (lineDetailInfo.lineItemId as string|number).toString())
    .then((resp) => {
      lineDetailInfo.lineForm = resp.data
    })
    .catch((err) => {
      $f.ui.showNotifyFailed($f.getAxiosErrMsg(err))
    })
    .finally(() => {
      lineLoadingState.value = false
    })
}

let lineSvrErrMsg = ref('')

// 明细帮助方法
const {
  lineDetailInfo,
  lineDetailStatus,
  lineDetailNav,
} = useLineDetailHelper(
  t('代码明细'),
  'codeLine',
  'codeDetail',
  null,
  loadLineModelData,
  showingTabPanel,
  lineSvrErrMsg,
  () => {
    v$.value.$reset()
  }
)

const {
  isLineViewMode,
  isLineCreateMode,
  isLineEditMode,
  isLineCreateOrEditMode,
  isLineViewOrEditMode,
  isLineTabDisp,
  tabTitle
} = lineDetailStatus

const validators = $f.validators

//明细验证
const rules = {
  codeValue: {
    required: validators.required
  },
  codeName1: {
    required: validators.required
  },
  sortId: {
    int32: validators.int32
  }
}

const v$ = useVuelidate(rules, computed(() => lineDetailInfo.lineForm as any), {$autoDirty: true})

// 新建明细
const createCodeLine = function () {
  lineDetailNav.goCreateLine({
    codeId: $d.form.codeId,
    sortId: null,
    codeValue: null,
    codeName1: null,
    codeName2: null,
    codeName3: null,
    codeName4: null,
    codeName5: null,
    isEnabled: true,
    descriptions: null
  })
}

// 删除明细
const deleteCodeLine = function (codeLineId: string | number | null) {
  void $f.ui.messageBox({
    caption: '操作确认',
    text: '确定要删除该明细吗?',
    icon: 'Warning',
    buttons: 'OkCancel',
    delayClose: true
  }).then((btn) => {
    if (btn === 'ok') {
      $f.axios
        .post('/comm/code/delete-codeline/' + codeLineId)
        .then(() => {
          $f.ui.closeMsgBox()
          loadModelData()
        })
        .catch((err) => {
          void $f.ui.messageBox({
            caption: '删除失败',
            text: $f.getAxiosErrMsg(err),
            icon: $f.getAxiosErrIcon(err),
            buttons: 'Close'
          })
        })
    }
  })
}

let submittingState = ref(false)
// 明细新建/编辑
const doCodeLineSubmit = function () {
  lineSvrErrMsg.value = ''
  void v$.value
    .$validate()
    .then((valRes) => {
      if (valRes) {
        if (isLineCreateMode.value) {
          submittingState.value = true
          $f.axios
            .post('/comm/code/create-codeline', lineDetailInfo.lineForm)
            .then(() => {
              lineDetailNav.backToListTab()
              loadModelData()
            })
            .catch((err) => {
              lineSvrErrMsg.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              submittingState.value = false
            })
        } else if (isLineEditMode) {
          submittingState.value = true
          $f.axios
            .post('/comm/code/update-codeline', lineDetailInfo.lineForm)
            .then(() => {
              lineDetailNav.doneLineEdit()
              loadModelData()
            })
            .catch((err) => {
              lineSvrErrMsg.value = $f.getAxiosErrMsg(err)
            })
            .finally(() => {
              submittingState.value = false
            })
        }
      }
    })
}

// region 初始化
let colsInfoSaved = loadDetailColOptions('codeLine', columnsInfoCodeLine)
columnsInfoCodeLine = colsInfoSaved[0]
$d.visibleColumnsCodeLine = colsInfoSaved[1]
$d.paginationInfoCodeLine.rowsPerPage = loadDetailPageSize('codeLine')

const fx = $f
const e$ = $f.getFieldErrStr
// endregion
</script>
